package com.lsh.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
@Component
public class RedisStringUtils {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 根据key获取value
     *
     * @param key
     * @return
     */
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
    /**
     * 向redis里存入数据和设置缓存时间
     *
     * @param key
     * @param value
     * @param time
     */
    public void set(String key, String value, long time) {
        stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    /**
     * 删除key
     * @param key
     * @return
     */
    public Boolean delete(String key){
        return stringRedisTemplate.delete(key);
    }

    /**
     * 设置无过期时间的数据
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key,value);
    }

    /**
     * 检查key是否存在
     *
     * @param key
     * @return
     */
    public Boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    /**
     * 设置过期时间
     *
     * @param key
     * @param time
     */
    public Boolean expire(String key, long time) {
        return stringRedisTemplate.expire(key, time, TimeUnit.MILLISECONDS);
    }

    /**
     * 根据key获取过期时间并换算成指定单位
     *
     * @param key
     * @return
     */
    public Long getExpire(String key) {
        return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 根据key查看集合中是否存在指定数据
     *
     * @param key
     * @param object
     * @return
     */
    public Boolean isMember(String key, Object object) {
        return stringRedisTemplate.opsForSet().isMember(key, object);
    }
}
